﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace PDO.DataPersistence.Core
{


    public static class LocalizationHelper
    {

        public delegate string LocalizingStringConverterCallback(string key, string twoLetterISOLanguageName, string fallbackMsg);

        private static LocalizingStringConverterCallback _localizingStringConverter;


        public static LocalizingStringConverterCallback LocalizingStringConverter
        {
            get { return LocalizationHelper._localizingStringConverter; }
            set { LocalizationHelper._localizingStringConverter = value; }
        }



        /// <summary>
        /// Retrieve a localized error message from the database, with a safety fallback message in case of db errors.
        /// </summary>
        /// <param name="key">The error message key.</param>
        /// <param name="fallbackMsg">Fallback message to be used if the key is not found or an error occurs.</param>
        /// <param name="args">Optional parameters for string.Fomat().</param>
        /// <returns>The error message string.</returns>
        public static string ErrorDefMsg(string key, string fallbackMsg, params object[] args)
        {
            string msg = fallbackMsg;
            try
            {
                // Use localizing converter, if provided.
                if (null != _localizingStringConverter)
                {
                    msg = _localizingStringConverter(key, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, fallbackMsg);
                }
                
                if (args != null && args.Length > 0)
                {
                    // Treat as format specifier
                    msg = string.Format(msg, args);
                }

            }
            catch(Exception ex)
            {
                msg += " Formatting error: " + ex.Message;
            }
            
            return msg;
        }

   }

}
